//index.js
const app = getApp()

Page({
  data: {
    motto: 'Hi，欢迎来到水木帮',
    avatarUrl: '',
    userInfo: {},
    logged: false,
    requestResult: '',
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  onLoad: function () {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
  
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },

  //获取用户信息
  onGetUserInfo: function (e) {
    if (!this.data.logged && e.detail.userInfo) {
      //调用云函数
      wx.cloud.callFunction({
        name: 'login',
        data: {},
        success: res => {
          e.detail.userInfo.openid = res.result.openid
          app.globalData.openid = res.result.openid
          this.setData({
            logged: true,
            avatarUrl: e.detail.userInfo.avatarUrl,
            userInfo: e.detail.userInfo,
          })
          wx.setStorageSync('userInfo', e.detail.userInfo)
          console.log('调用login云函数返回的userinfo', e.detail.userInfo)
          //跳转到首页
          wx.switchTab({ url: '../home/home' })
        },
        fail: err => {
          console.error('[云函数] [login] 调用失败', err)
        }
      })
    }
  },
})
